package com.base.util;

import android.util.Log;

import com.loyal.core.helper.StreamHelper;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RootShell {
    private static final String TAG = "Base.RootShell";

    /**
     * 执行命令获取返回结果
     */
    public static String execCmd(String cmdStr) {
        Log.w(TAG, "run " + cmdStr);
        Process process = null;
        DataOutputStream os = null;
        StringBuilder resultBuilder = new StringBuilder();
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmdStr + "\n");
            os.writeBytes("exit\n");
            os.flush();

            //获取返回值
            InputStream is = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                resultBuilder.append(line).append(line.endsWith("\n") ? "" : "\n");
            }
            is.close();
            reader.close();
            process.waitFor();
            process.destroy();
        } catch (Exception e) {
            Log.e(TAG, "execCmd", e);
            return "";
        } finally {
            StreamHelper.close(os);
            try {
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultBuilder.toString();
    }
}
